import React, {Component, InputHTMLAttributes} from "react";
import FieldContext from "./FieldContext";

interface IIProps {
  name: string;
  children: any
}

export default class Field extends Component<IIProps> {
  unregisterFieldEntry!: Function;
  declare context: React.ContextType<typeof FieldContext>;

  static contextType = FieldContext

  componentDidMount() {
    if(this.context?.registerFieldEntity) {
      this.unregisterFieldEntry = this.context.registerFieldEntity(this)
    }
  }

  componentWillUnmount(): void {
    this.unregisterFieldEntry()
  }

  onStoreChange = () => {
    this.forceUpdate()
  }


  getControlled = () => {
    const { getFieldValue, setFieldsValue } = this.context
    const { name } = this.props
    return {
      value: getFieldValue(name),
      onChange: (e: React.FormEvent<HTMLInputElement>) => {
        const newVal = e.currentTarget.value
        setFieldsValue({[name]: newVal})
      }
    }
  }



  render() {
    const {children} = this.props

    return React.cloneElement(children, this.getControlled())
  }
}